package cn.geminis.crypto.core.x509;

import cn.geminis.crypto.core.key.PublicKey;
import cn.geminis.crypto.core.util.EncodeUtils;
import cn.geminis.crypto.csp.AbstractSigner;
import org.bouncycastle.asn1.pkcs.CertificationRequest;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;

/**
 * @author Allen
 */
public class CertRequest {

    private PKCS10CertificationRequest request;

    private String subject;
    private PublicKey publicKey;

    public CertRequest() {

    }

    public CertRequest(byte[] data) {
        CertificationRequest req = CertificationRequest.getInstance(data);
        this.request = new PKCS10CertificationRequest(req);
        this.subject = this.request.getSubject().toString();
        this.publicKey = new PublicKey(this.request.getSubjectPublicKeyInfo());
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public PublicKey getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(PublicKey publicKey) {
        this.publicKey = publicKey;
    }

    public void generate(AbstractSigner signer) {
        X500Name subjectName = new X500Name(new Utf8Style(), this.subject);
        PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(
                subjectName,
                this.publicKey.getSubjectPublicKeyInfo());
        signer.init(true, null);
        this.request = builder.build(signer.createContentSigner());
    }

    public byte[] getEncode() {
        return EncodeUtils.toDER(this.request.toASN1Structure());
    }

    public String getFormat() {
        return EncodeUtils.toPEM(this.request);
    }

}
